package com.paschino.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.paschino.modal.News;

@Repository
public class NewsDAOImpl extends AbstractDAO implements NewsDAO{
	
	@Override
	public boolean addNews(News news) {
		getSession().saveOrUpdate(news);
		if (news.getId() > 0) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<News> getNewsList() {
		List<News> newsList = new ArrayList<News>();
		Query query = getSession().createQuery("from News n where (n.isDelete is null or n.isDelete = false)");
		newsList = query.list();
		return newsList;
	}

	@Override
	public News getNews(int newsId) {
		return (News) getSession().get(News.class, newsId);
	}

	@Override
	public boolean updateNews(News news) {
		String name = news.getName();
		getSession().update(news);
		if (name.equals(news.getName())) {
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<News> getTopNewsHomePage(){
		List<News> newsList = new ArrayList<News>();
		Query query = getSession().createQuery("from News n where (n.isDelete is null or n.isDelete = false) and n.isActive = true order by n.id desc limit 3");
		newsList = query.list();
		return newsList;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<News> getNewsListHomePage(){
		List<News> newsList = new ArrayList<News>();
		Query query = getSession().createQuery("from News n where (n.isDelete is null or n.isDelete = false) and n.isActive = true order by n.id desc limit 10");
		newsList = query.list();
		return newsList;
	}
	
	@Override
	public int deleteNews(int newsID){
		Query query = getSession().createQuery("update News n set n.isDelete = true where n.id = :newsID");
		query.setParameter("newsID", newsID);
		int result = query.executeUpdate();
		return result;
	}
	
	@Override
	public int hideNews(int newsID){
		Query query = getSession().createQuery("update News n set n.isActive = false where n.id = :newsID");
		query.setParameter("newsID", newsID);
		int result = query.executeUpdate();
		return result;
	}

	@Override
	public int unhideNews(int newsID){
		Query query = getSession().createQuery("update News n set n.isActive = true where n.id = :newsID");
		query.setParameter("newsID", newsID);
		int result = query.executeUpdate();
		return result;
	}


}
